package com.levi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.levi.enums.EnumUtil;
import com.levi.form.UserLoginForm;
import com.levi.mall.mapper.UserMapper;
import com.levi.mall.service.UserService;
import com.levi.pojo.User;
import com.levi.vo.ResponseVo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author shentong
 * @since 2022/3/22 9:19 PM
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public ResponseVo<User> register(User user) {
        LambdaQueryWrapper<User> ew1 = new LambdaQueryWrapper<>();
        ew1.eq(User::getUsername, user.getUsername());
        int usernameCount = this.count(ew1);
        if (usernameCount > 0) {
            return ResponseVo.error(EnumUtil.USER_EXIST);
        }
        LambdaQueryWrapper<User> ew2 = new LambdaQueryWrapper<>();
        ew2.eq(User::getEmail, user.getEmail());
        int emailCount = this.count(ew2);
        if (emailCount > 0) {
            return ResponseVo.error(EnumUtil.EMAIL_EXIST);
        }
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        user.setRole(EnumUtil.CUSTOMER.getCode());
        this.save(user);
        return ResponseVo.success();
    }


    @Override
    public ResponseVo<User> login(UserLoginForm userLoginForm) {
        LambdaQueryWrapper<User> ew = new LambdaQueryWrapper<>();
        ew.eq(User::getUsername, userLoginForm.getUsername());
        User user = this.getOne(ew);
        if (user == null) {
            return ResponseVo.error(EnumUtil.USERNAME_OR_PASSWORD_ERROR);
        }
        if (!user.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(userLoginForm.getPassword().getBytes(StandardCharsets.UTF_8)))) {
            ResponseVo.error(EnumUtil.USERNAME_OR_PASSWORD_ERROR);
        }
        user.setPassword("");
        return ResponseVo.success(user);
    }



}
